# -*- coding: utf-8 -*-
# @File:     rabbitmq_queue.py
# @Author:
# @DateTime: 2025/06/10/16:20


import threading
import time
import traceback
import json
from pika.exceptions import StreamLostError, ConnectionClosedByBroker, AMQPConnectionError, ChannelWrongStateError
import pika

from app.api.generate.utils.process_generate_progress import process_generate_progress
from app.api.generate.utils.process_generate_result import process_generate_result
from app.conf import settings


# 优先级队列10
queue_arguments = {"x-max-priority": 10}


def init_rabbit_serve():
    # 1 链接rabbitmq
    credentials = pika.PlainCredentials(settings.RABBITMQ_USER, settings.RABBITMQ_PWD)
    connection = pika.BlockingConnection(pika.ConnectionParameters(settings.RABBITMQ_HOST, port=settings.RABBITMQ_PORT, credentials=credentials))
    channel = connection.channel()

    # 2 创建队列  如果已经有这个队列就不执行  如果生产者没有这个队列就创建一个队列
    channel.queue_declare(queue=settings.RABBITMQ_QUEUE_LIST[0], arguments=queue_arguments, durable=True)
    # 2 创建队列  如果已经有这个队列就不执行  如果生产者没有这个队列就创建一个队列
    channel.queue_declare(queue=settings.RABBITMQ_QUEUE_LIST[1], arguments=queue_arguments, durable=True)
    # 设置为空闲取消息
    channel.basic_qos(prefetch_count=1)
    return channel, connection


def queue_send_message(data: dict, queue_name: str, priority: int = 1) -> None:
    credentials1 = pika.PlainCredentials(settings.RABBITMQ_USER, settings.RABBITMQ_PWD)
    connection1 = pika.BlockingConnection(pika.ConnectionParameters(settings.RABBITMQ_HOST, port=settings.RABBITMQ_PORT, credentials=credentials1))
    ch = connection1.channel()
    print("send message")
    ch.queue_declare(queue=queue_name, arguments=queue_arguments, durable=True)
    ch.basic_publish(exchange='',
                     routing_key=queue_name,  # 指定队列
                     body=json.dumps(data),
                     properties=pika.BasicProperties(delivery_mode=2, priority=priority)  # 设置持久化缓存和优先级为1
                     )
    connection1.close()


# 定义回调结果函数
def callback_result(ch, method, properties, body):
    # 具体操作....
    data = json.loads(body.decode("utf-8"))
    process_generate_result(data)

    ch.basic_ack(delivery_tag=method.delivery_tag)


# 定义回调进程函数
def callback_progress(ch, method, properties, body):
    # 具体操作....
    data = json.loads(body.decode("utf-8"))
    process_generate_progress(data)
    ch.basic_ack(delivery_tag=method.delivery_tag)


def start_serve():

    # 监听配置  有数据后执行回调
    connection = None
    while True:
        try:
            channel, connection = init_rabbit_serve()

            channel.basic_consume(queue=settings.RABBITMQ_QUEUE_LIST[0],
                                  # auto_ack=True,  # 默认应答模式
                                  on_message_callback=callback_result)  # 回调函数
            # 监听配置  有数据后执行回调
            channel.basic_consume(queue=settings.RABBITMQ_QUEUE_LIST[1],
                                  # auto_ack=True,  # 默认应答模式
                                  on_message_callback=callback_progress)  # 回调函数
            print("rabbitMQ start")
            # 启动监听
            channel.start_consuming()

        except StreamLostError:
            print("rabbitMQ Connection lost, reconnecting...")
            time.sleep(5)  # 等待后重试
            continue
        except ChannelWrongStateError:
            print("chanel error, reconnecting...")
            time.sleep(10)  # 等待后重试
            continue
        except AMQPConnectionError:
            print("rabbitMQ close, reconnecting...")
            time.sleep(10)  # 等待后重试
            continue
        except KeyboardInterrupt:
            break
        except Exception as e:
            print(f"Unexpected error: {e}")
            break
        finally:
            if connection and not connection.is_closed:
                connection.close()
                print("Connection closed.")

def start_loop():
    t = threading.Thread(target=start_serve)
    t.daemon = True
    t.start()

consumer = start_loop()


def del_queue_message(queue_name, record_id_list):

    try:
        channel, connection = init_rabbit_serve()

        # 声明队列
        channel.queue_declare(queue=queue_name, arguments=queue_arguments, durable=True)

        # 获取队列中的消息数量
        queue_state = channel.queue_declare(queue=queue_name, passive=True)
        message_count = queue_state.method.message_count
        # print(f"队列 '{queue_name}' 中有 {message_count} 条消息正在等待。")
        # 删除队列中的所有消息
        for _ in range(message_count):
            method_frame, header_frame, body = channel.basic_get(queue=queue_name)
            data = json.loads(body.decode("utf-8"))
            msg_record_id = data.get('record_id')
            # print(msg_record_id)
            if msg_record_id in record_id_list:
                print(f"del {queue_name} message: {msg_record_id}")
                channel.basic_ack(delivery_tag=method_frame.delivery_tag)
            else:
                pass
        # 关闭连接
        connection.close()
    except:
        print(traceback.format_exc())








